import base64
import hashlib
import os
import random
import re
import requests
import threading
import time
import string
from functools import wraps

from flask import request, session, Response, Blueprint, jsonify, make_response, render_template, g
from flask_mail import Message

# from app.service.imageFunction import gene_code
# from OperationPlatform.settings import BASE_DIR
# from app.service.sendMailFunction import eMailClass
from sqlalchemy import desc

from app.utils import getClientIp
from app.utils.authority import exception_handling
from .models import *
from app import app, db
from exts import _isLogin, mail
from app.utils.error import ResponseError

Api = Blueprint('api', __name__, template_folder='templates')


@Api.route('/')
def api_index():
    return jsonify()


@Api.route('/login.do', methods=['post'])
@exception_handling
def api_login_do():
    username = request.values.get('username')
    password = request.values.get('password')
    if not username or not password:
        raise ResponseError(1, '账户或密码为空')
    user = QUserInfo.query.filter_by(username=username).first()
    if not user:
        raise ResponseError(2, '账户或密码错误')
    reData = user.verify_password(password)
    history = QUserLoginHistory(
        userid=username,
        time=int(time.time()),
        ip=getClientIp(),
    )
    if not reData:
        history.status = '密码错误'
        db.session.add(history)
        db.session.commit()
        raise ResponseError(3, '账户或密码错误')
    history.status = '登陆成功'
    db.session.add(history)
    db.session.commit()
    g.user = user
    token = user.generate_auth_token().decode()
    return jsonify(data={'token': token, 'username': username, 'name': user.name})


@Api.route('/index.do', methods=['post'])
@exception_handling
@_isLogin
def api_index_do():
    user = g.user
    history = QUserLoginHistory.query.filter_by(userid=user.username).order_by(desc('time')).first()
    user_count = QUserInfo.query.count()

    return jsonify(data={'history': history.to_dict(), 'user': user.to_dict(),
                         'summary': {'user': user_count, 'circuit': 0, 'cabinet': 0}})
